<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="IP" prop="ip">
        <el-input v-model="queryParams.ip" placeholder="请输入IP" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.training_pool_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <!-- 不需要进行显示操作功能
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['training:pool:add']"
              >新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['training:pool:edit']"
              >修改
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['training:pool:remove']"
              >删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['training:pool:export']"
              >导出
              </el-button>
            </el-col>
      -->
      <el-col :span="1.5">
        <el-button v-hasPermi="['training:pool:modifyIpRange']" type="primary" plain
          @click="handleChangeIpRange">更改IP池范围</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="poolList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" width="100" />
      <el-table-column label="IP" align="center" prop="ip" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.training_pool_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['training:pool:edit']"
                >修改
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['training:pool:remove']"
                >删除
                </el-button>
              </template>
            </el-table-column>-->
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog title="修改ip池范围" :visible.sync="ipPoolRangeVisible" width="500px" append-to-body>
      <el-form ref="rangeForm" :model="rangeForm" :rules="rangeRules" label-width="80px">
        <el-form-item label="ip起始值" prop="startIp">
          <el-input v-model="rangeForm.startIp" placeholder="请输入ip池范围" />
        </el-form-item>
        <el-form-item label="范围" prop="range">
          <el-input type="number" v-model="rangeForm.range" placeholder="请输入ip池范围" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitRangeForm">确 定</el-button>
          <el-button @click="ipPoolRangeVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 添加或修改IP池对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="IP" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入IP" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.training_pool_status" :key="dict.value" :label="parseInt(dict.value)">{{
              dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPool, getPool, delPool, addPool, updatePool, changeIpPool } from "@/api/training/pool"

export default {
  name: "Pool",
  dicts: ['training_pool_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // IP池表格数据
      poolList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      ipPoolRangeVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ip: null,
        status: null
      },
      // 范围表单参数
      rangeForm: {},
      rangeRules: {
        startIp: [
          { required: true, message: "请输入IP地址", trigger: "blur" },
          { validator: this.validateIp, trigger: "blur" }
        ],
        range: [
          { required: true, message: "请输入IP范围", trigger: "blur" },
          //自定义校验规则
          { validator: this.validateIpRange, trigger: "blur" }
        ]
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ip: [
          { required: true, message: "IP不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    validateIpRange(rule, value, callback) {
      //正则表达式判断是否为正确的ip地址
      const ipRegex = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;
      if (!ipRegex.test(value)) {
        callback(new Error("请输入正确的IP地址"));
      } else {
        callback();
      }
    },
    validateIpRange(rule, value, callback) {
      //判断是否是合法的IP
      if (!value) {
        callback(new Error('请输入IP范围'))
      } else {
        const ipaddrs = this.rangeForm.startIp.split(".")
        const lastNum = Number(ipaddrs[ipaddrs.length - 1])
        console.log(lastNum,value)
        console.log(lastNum+Number(value))
        if (lastNum + Number(value) < 255) {
          callback()
        } else {
          callback(new Error('请输入正确的IP范围，不可超过255 '+(lastNum +Number(value))))
        }
      }
    },
    handleChangeIpRange() {
      this.resetRangeForm()
      this.ipPoolRangeVisible = true
    },
    resetRangeForm() {
      this.rangeForm = {
        startIp: "",
        range: 0,
      }
    },
    /** 查询IP池列表 */
    getList() {
      this.loading = true
      listPool(this.queryParams).then(response => {
        this.poolList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ip: null,
        status: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加IP池"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPool(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改IP池"
      })
    },
    submitRangeForm() {
      this.$refs['rangeForm'].validate(valid => {
        if (valid) {
          changeIpPool(this.rangeForm).then(response => {
            this.$modal.msgSuccess("修改ip池范围成功");
            this.ipPoolRangeVisible = false;
            this.getList();
          })
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePool(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPool(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除IP池编号为"' + ids + '"的数据项？').then(function () {
        return delPool(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('training/pool/export', {
        ...this.queryParams
      }, `pool_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
